import wordcloud
# 构建词云对象w，设置词云图片宽、高、字体、背景颜色等参数
w = wordcloud.WordCloud(width=1000,height=700,background_color='white',font_path='msyh.ttc')
# 调用词云对象的generate方法，将文本传入
w.generate('从明天起，做一个幸福的人。喂马、劈柴，周游世界。从明天起，关心粮食和蔬菜。我有一所房子，面朝大 海，春暖花开')
# 将生成的词云保存为output2-poem.png图片文件，保存到当前文件夹中
w.to_ﬁle('output2-poem.png')



# 导入词云制作库wordcloud和中文分词库jieba
import jieba
import wordcloud
# 导入imageio库中的imread函数，并用这个函数读取本地图片，作为词云形状图片
import imageio
mk = imageio.imread("wujiaoxing.png")
w = wordcloud.WordCloud(mask=mk)
# 构建并配置词云对象w，注意要加scale参数，提高清晰度
w = wordcloud.WordCloud(width=1000,
                        height=1000,
                        background_color='red',
                        font_path='msyh.ttc',
                        mask=mk,scale=15)
# 对来自外部文件的文本进行中文分词，得到string
f = open('关于实施乡村振兴战略的意见.txt',encoding='utf-8')
txt = f.read()
txtlist = jieba.lcut(txt)
string = " ".join(txtlist)
# 将string变量传入w的generate()方法，给词云输入文字
w.generate(string)
# 将词云图片导出到当前文件夹
w.to_file('output6-village.png')



# 导入词云制作库wordcloud
import wordcloud
# 将外部文件包含的文本保存在string变量中
string = open('hamlet.txt').read()
# 导入imageio库中的imread函数，并用这个函数读取本地图片，作为词云形状图片
import imageio
mk = imageio.imread("alice.png")
# 构建词云对象w，注意增加参数contour_width和contour_color设置轮廓宽度和颜色
w = wordcloud.WordCloud(background_color="black",
                        mask=mk,
                        contour_width=1,
                        contour_color='steelblue')
# # 将string变量传入w的generate()方法，给词云输入文字
w.generate(string)
# 将词云图片导出到当前文件夹
w.to_ﬁle('output9-contour.png')




# 导入绘图库matplotlib和词云制作库wordcloud
import matplotlib.pyplot as plt
from wordcloud import WordCloud,ImageColorGenerator
# 将外部文件包含的文本保存在text变量中
text = open('hamlet.txt').read()
# 导入imageio库中的imread函数，并用这个函数读取本地图片queen2.jﬁf，作为词云形状图片
import imageio
mk = imageio.imread("alice_color.png")
# 构建词云对象w
wc = WordCloud(background_color="white",
               mask=mk,)
# 将text字符串变量传入w的generate()方法，给词云输入文字
wc.generate(text)
# 调用wordcloud库中的ImageColorGenerator()函数，提取模板图片各部分的颜色
image_colors = ImageColorGenerator(mk)

# 显示原生词云图、按模板图片颜色的词云图和模板图片，按左、中、右显示
ﬁg, axes = plt.subplots(1, 3) # 最左边的图片显示原生词云图
axes[0].imshow(wc) # 中间的图片显示按模板图片颜色生成的词云图，采用双线性插值的方法显示颜色
axes[1].imshow(wc.recolor(color_func=image_colors),
               interpolation="bilinear")
# 右边的图片显示模板图片
axes[2].imshow(mk, cmap=plt.cm.gray)
for ax in axes:ax.set_axis_oﬀ()
plt.show()
# 给词云对象按模板图片的颜色重新上色
wc_color = wc.recolor(color_func=image_colors)
# 将词云图片导出到当前文件夹
wc_color.to_ﬁle('output10-alice.png')






# 导入词云制作库wordcloud和中文分词库jieba
import jieba
import wordcloud

# 导入imageio库中的imread函数，并用这个函数读取本地图片，作为词云形状图片
import imageio
mk = imageio.imread("chinamap.png")

# 构建并配置两个词云对象w1和w2，分别存放积极词和消极词
w1 = wordcloud.WordCloud(width=1000,
                         height=700,
                         background_color='white',
                         font_path='msyh.ttc',
                         mask=mk,
                         scale=15)
w2 = wordcloud.WordCloud(width=1000,
                         height=700,
                         background_color='white',
                         font_path='msyh.ttc',
                         mask=mk,
                         scale=15)

# 对来自外部文件的文本进行中文分词，得到积极词汇和消极词汇的两个列表
f = open('金庸小说.txt',encoding='utf-8')
txt = f.read()
txtlist = jieba.lcut(txt)
positivelist = []
negativelist = []
# 下面对文本中的每个词进行情感分析，情感>0.96判为积极词，情感<0.06判为消极词
print('开始进行情感分析，请稍等，三国演义全文那么长的文本需要三分钟左右')
# 导入自然语言处理第三方库snownlp
import snownlp
for each in txtlist:
    each_word = snownlp.SnowNLP(each)
    feeling = each_word.sentiments
    if feeling > 0.96:
        positivelist.append(each)
    elif feeling < 0.06:
        negativelist.append(each)
    else:
        pass
# 将积极和消极的两个列表各自合并成积极字符串和消极字符串，字符串中的词用空格分隔
positive_string = " ".join(positivelist)
negative_string = " ".join(negativelist)
# 将string变量传入w的generate()方法，给词云输入文字
w1.generate(positive_string)
w2.generate(negative_string)
# 将积极、消极的两个词云图片导出到当前文件夹
w1.to_ﬁle('output12-positive.png')
w2.to_ﬁle('output12-negative.png')
print('词云生成完成')





# 导入wordcloud库，并定义两个函数
from wordcloud import (WordCloud, get_single_color_func)


class SimpleGroupedColorFunc(object):
    """Create a color function object which assigns EXACT colors
    to certain words based on the color to words mapping

    Parameters
    ---------
    color_to_words : dict(str -> list(str))
    A dictionary that maps a color to the list of words.

    default_color : str
    Color that will be assigned to a word that's not a member
    of any value from color_to_words.
"""

def __init__(self, color_to_words, default_color):
    self.word_to_color = {word: color
                for (color, words) in color_to_words.items()
                for word in words}

    self.default_color = default_color

    def __call__(self, word, **kwargs):
        return self.word_to_color.get(word, self.default_color)

class GroupedColorFunc(object):
    """Create a color function object which assigns DIFFERENT SHADES of
    speciﬁed colors to certain words based on the color to words mapping.

    Uses wordcloud.get_single_color_func

    Parameters
    ---------
    color_to_words : dict(str -> list(str))
    A dictionary that maps a color to the list of words.

    default_color : str
    Color that will be assigned to a word that's not a member
    of any value from color_to_words.
    """

    def __init__(self, color_to_words, default_color):

        self.color_func_to_words = [
            (get_single_color_func(color), set(words))
            for (color, words) in color_to_words.items()]
        self.default_color_func = get_single_color_func(default_color)
    def get_color_func(self, word):
        """Returns a single_color_func associated with the word"""
        try:
            color_func = next(
                color_func for (color_func,words) in self.color_func_to_words
                if word in words)
            except StopIteration:(
                color_func) = self.default_color_func

            return color_func
        def __call__(self, word, **kwargs):
            return self.get_color_func(word)(word, **kwargs)

# 导入imageio库中的imread函数，并用这个函数读取本地图片，作为词云形状图片
import imageio
mk = imageio.imread("chinamap.png")

w = WordCloud(
    width=1000,
    height = 700,
    background_color = 'white',
    font_path = 'msyh.ttc',
    mask = mk,
    scale = 15,
    max_font_size = 60,
    max_words = 20000,
    font_step = 1)

import \
    jieba  # 对来自外部文件的文本进行中文分词，得到string f = open('三国演义.txt',encoding='utf-8') txt = f.read() txtlist = jieba.lcut(txt) string = " ".join(txtlist)

# 将string变量传入w的generate()方法，给词云输入文字 w.generate(string)

# 创建字典，按人物所在的不同阵营安排不同颜色，绿色是蜀国，橙色是魏国，紫色是东吴，粉色是诸侯群雄 color_to_words = {    'green': ['刘备','刘玄德','孔明','诸葛孔明', '玄德', '关公', '玄德曰','孔明曰',              '张飞', '赵云','后主', '黄忠', '马超', '姜维', '魏延', '孟获',              '关兴','诸葛亮','云长','孟达','庞统','廖化','马岱'],    'red': ['曹操', '司马懿', '夏侯', '荀彧', '郭嘉','邓艾','许褚',            '徐晃','许诸','曹仁','司马昭','庞德','于禁','夏侯渊','曹真','钟会'],    'purple':['孙权','周瑜','东吴','孙策','吕蒙','陆逊','鲁肃','黄盖','太史慈'],    'pink':['董卓','袁术','袁绍','吕布','刘璋','刘表','貂蝉'] }

# 其它词语的颜色 default_color = 'gray'

# 构建新的颜色规则 grouped_color_func = GroupedColorFunc(color_to_words, default_color)

# 按照新的颜色规则重新绘制词云颜色
w.recolor(color_func=grouped_color_func)

# 将词云图片导出到当前文件夹 w.to_ﬁle('output13-threekingdoms.png')